package com.kdd.campus.sh.service.impl;

import com.kdd.campus.sh.convert.CommentConvert;
import com.kdd.campus.sh.dao.ShCommentMapper;
import com.kdd.campus.sh.dao.UserMapper;
import com.kdd.campus.sh.dto.CommentDto;
import com.kdd.campus.sh.po.ShComment;
import com.kdd.campus.sh.po.User;
import com.kdd.campus.sh.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Auther: fcp
 * @Date: 2020/4/13 17:45
 * @Description:
 */
@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private ShCommentMapper commentMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void add(ShComment comment) {
        if (comment.getReplayCommentId() == null){
            // 如果没有回复别人，说明是第一条留言消息，生成唯一的组groupNum
            comment.setGroupNum(UUID.randomUUID().toString());
            comment.setIsFirst(true);
        }else {
            // 不是第一条留言，groupNum由前端传入
            comment.setIsFirst(false);
        }
        comment.setStatus(1);
        comment.setCreateTime(new Date());
        commentMapper.insert(comment);
    }

    @Override
    public void delete(Long userId, Long commentId) {
        ShComment comment = ShComment.builder().status(0).build();

        Example example = new Example(ShComment.class);
        example.createCriteria()
                .andEqualTo("id", commentId)
                .andEqualTo("userId",userId).orEqualTo("replayCommentId",commentId);

        commentMapper.updateByExampleSelective(comment, example);
    }

    @Override
    public List<CommentDto> findByProductId(Long productId, Long userId) {
        List<ShComment> shCommentList = commentMapper.findByProductId(productId);
        List<CommentDto> commentDtoList = new ArrayList<>();
        shCommentList.forEach(shComment -> {
            // 用类型转换器
            User user = userMapper.selectByPrimaryKey(shComment.getUserId());
            CommentDto commentDto = CommentConvert.INSTANCE.poToDto(shComment);
            if (userId==commentDto.getUserId()){ commentDto.setCanDelete(true); }   //当前用户是否有权力对该留言进行删除
            commentDto.setUsername(user.getUsername()).setHeadPortrait(user.getHeadPortrait());

            commentDtoList.add(commentDto);
        });

        return commentDtoList;
    }
}


